<!--
 * @Author: zhouyankai 4848494717@qq.com
 * @Date: 2025-06-18 15:51:51
 * @LastEditors: zhouyankai 4848494717@qq.com
 * @LastEditTime: 2025-07-11 18:05:48
 * @FilePath: \BusStopBoard.Appc:\Users\szfinest-11\Desktop\室内导航demo\uni-preset-vue-vite-ts\src\pages\index\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="container">
    <web-view id="web-view-1" src="http://10.254.61.107:5174" @message="onWebMessage" @load="onWebLoad">
    </web-view>
  </view>
  <!-- <div class="btns">
            <button @click.stop.prevent="start">获取当前位置</button>
    </div> -->
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';

const wangye = ref("")

let webViewContext = null

function onWebLoad(e) {
  console.log(e, '我是webview')
  webViewContext = e;
}

// 接收网页消息
function onWebMessage(e) {
  const msg = e.detail.data;
  console.log(e, '我收到消息了呢')
  if (msg.action === 'scanBluetooth') {
    //   this.startBluetoothScan();
    uni.showModal({
      title: '提示',
      content: '这是一个模态弹窗',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定');
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
    console.log(msg, '我接受到消息额')
  }
}
function start() {
  console.log('我点击了呢')

  uni.postMessage({
    data: {
      action: 'message'
    }
  });

  searchIb()
}


// console.log(wangye,'我得到消息了呢')

onMounted(() => {
  // searchIb()
  // setTimeout(() => {
  //     //  console.log(webViewContext,'我得到消息了呢')
  //     webViewContext.postMessage({'sendToWebView': '1'}); 
  // }, 3000);

  //  uni.postMessage({
  //     data: {
  //         action: 'message'
  //     }
  //  });
  initWeb()
})

function initWeb() {
  // console.log('你在交换什么')
  // uni.connectSocket({
  //   url: 'ws://10.254.61.107:8898/demo',
  // });
  // uni.onSocketOpen(function (res) {
  //   console.log('WebSocket连接已打开！');
  // });
  // uni.onSocketError(function (res) {
  //   console.log('WebSocket连接打开失败，请检查！');
  // });
  var socketOpen = false;
  var socketMsgQueue = [];

  uni.connectSocket({
    url: 'ws://10.254.61.107:8898/demo',
  });

  uni.onSocketOpen(function (res) {
    socketOpen = true;
    for (var i = 0; i < socketMsgQueue.length; i++) {
      sendSocketMessage(socketMsgQueue[i]);
    }
    socketMsgQueue = [];
  });

  function sendSocketMessage(msg) {
    if (socketOpen) {
      uni.sendSocketMessage({
        data: msg
      });
    } else {
      socketMsgQueue.push(msg);
    }
  }





  // var socketTask = uni.connectSocket({
  //   url: 'ws://10.254.61.107:8898/demo',
  //   complete: () => {
  //     setTimeout(() => {
  //       socketTask.send({
  //         data: '{"action": "message"}',
  //         success: function (res) {
  //           console.log(res, '我发送消息成功啦')
  //         },
  //         fail: function (res) {
  //           console.log(res, '我发送消息失败了')
  //         }
  //       })
  //     }, 3000);
  //     console.log('我连接成功啦')
  //   }
  // });



  // socketTask.onOpen = (event) => {
  //   console.log(event, '我打开连接')
  // }
  // socketTask.onMessage = (event) => {
  //   console.log(event, '我收到消息了')
  // }
  // socketTask.onError = (event) => {
  //   console.log(event, '我错误了')
  // }
  // socketTask.onClose = (event) => {
  //   console.log(event, 'onclose 执行关闭事件');
  // }
}


function searchIb() {

  // 存储不同Beacon的滤波器实例
  const beaconFilters = {};
  // RSSI转距离函数
  function calculateDistance(rssi, measuredPower = -61, n = 2) {
    if (rssi >= 0) return -1; // 无效值

    // 对数路径损耗模型
    const ratio = (measuredPower - rssi) / (10 * n);
    return Math.pow(10, ratio);
  }
  // 启动 iBeacon 扫描
  wx.startBeaconDiscovery({
    uuids: ['FDA50693-A4E2-4FB1-AFCF-C6EB07647825'],
    success: res => {
      console.log("附近的 iBeacon 设备", res);
      // const kf = new KalmanFilter();
      // const asda = {}
      // 注册信标更新监听事件
      wx.onBeaconUpdate(function (res) {
        const beacons = res.beacons;
        // beacons.forEach(beacon => {
        //   const key = `${beacon.minor}`;

        //   // 初始化滤波器
        //   if (!beaconFilters[key]) {
        //     beaconFilters[key] = new KalmanFilter()
        //   }

        //   // beaconFilters[key].push(beacon.rssi)

        //   // RSSI转距离
        //   // const rawDistance = calculateDistance(beacon.rssi);



        //   // 卡尔曼滤波
        //   const filteredDistance = beaconFilters[key].filter(beacon.rssi)

        //   console.log("原始", beacon.rssi, '卡尔曼滤波后', filteredDistance)

        //   const rawDistance = calculateDistance(filteredDistance);

        //   // 使用滤波后的距离
        //   console.log(`Beacon ${key}:`, rawDistance, '米');
        // });

        const padp = beacons.map(beacon => {

          const key = `${beacon.minor}`;

          // 初始化滤波器
          if (!beaconFilters[key]) {
            beaconFilters[key] = {
              Kalman: null,
              data: [],
              CHANGD: 0
            }
            beaconFilters[key].Kalman = new KalmanFilter()
            beaconFilters[key].data = []
          }


          if (beacon.rssi !== 0) {
            beaconFilters[key].data.push(beacon.rssi)
            // 卡尔曼滤波
            const filteredDistance = beaconFilters[key].Kalman.filter(beacon.rssi)
            // console.log("原始", beacon.rssi, '卡尔曼滤波后', filteredDistance)
            const rawDistance = calculateDistance(filteredDistance, -61, 1.1744);
            beaconFilters[key].rawDistance = filteredDistance
            beaconFilters[key].CHANGD = rawDistance
            // 使用滤波后的距离
            console.log(key, filteredDistance, '卡慢炖之后的值');
            console.log(beaconFilters[key], '我是数据呢');
          }

          return {
            ...beacon,
            jili: beaconFilters[key].rawDistance,
            CHANGD: beaconFilters[key].CHANGD,
          }

          // beaconFilters[key].data.push(beacon.rssi)

          // // RSSI转距离
          // // const rawDistance = calculateDistance(beacon.rssi);



          // // 卡尔曼滤波
          // const filteredDistance = beaconFilters[key].Kalman.filter(beacon.rssi)

          // // console.log("原始", beacon.rssi, '卡尔曼滤波后', filteredDistance)

          // const rawDistance = calculateDistance(filteredDistance, -61, 1.407052115246173);

          // // 使用滤波后的距离
          // console.log(key, beaconFilters[key].data, '我是存储的值', filteredDistance, '卡慢炖之后的值');

          // return {
          //   ...beacon,
          //   jili: rawDistance
          // }
        })

        console.log(padp, '我是爱哭的')


      });
      // setInterval(() => {
      // 	// 获取扫描到的所有 iBeacon 设备
      // 	wx.getBeacons({
      // 		success: function(res) {
      // 			console.log('最终===>获取所有已搜索到的 iBeacon 设备');
      // 			console.log(res);
      // 		},
      // 		fail: function(err) {
      // 			console.log('最终===>获取所有已搜索到的 iBeacon 失败');
      // 			console.log(err);
      // 		}
      // 	});
      // }, 5000); // 5000 毫秒 = 5 



    },
    fail: res => {
      console.log("附近的 iBeacon 设备失败", res);
    }
  });
  // 超时停止扫描
  setTimeout(function () {
    wx.stopBeaconDiscovery({
      success: function () {
        console.log("停止设备扫描！");
        //console.log(devices);
      }
    });
  }, 200 * 1000);
}



</script>

<style>
.btns {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
}

.close-view {

  position: fixed;

  z-index: 99999;

  top: 30rpx;

  left: 45vw;

}
</style>
